package com.zros.modules.system.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import springfox.documentation.annotations.ApiIgnore;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zros.common.api.vo.PageResult;
import com.zros.common.api.vo.Result;
import com.zros.common.exception.JeecgBootException;
import com.zros.modules.business.entity.Clue;
import com.zros.modules.business.entity.UpdateRecord;
import com.zros.modules.business.service.IClueService;
import com.zros.modules.business.service.IUpdateRecordService;
import com.zros.modules.shiro.authc.util.JwtUtil;
import com.zros.modules.system.dto.CreateUser;
import com.zros.modules.system.dto.QueryUser;
import com.zros.modules.system.dto.UpdateUser;
import com.zros.modules.system.dto.UserInfo;
import com.zros.modules.system.entity.User;
import com.zros.modules.system.service.ITSysUserNumService;
import com.zros.modules.system.service.IUserService;

/**
 * @ClassName: UserController
 * @Description: User前端控制器
 * 
 * @date 2018年5月18日 下午4:03:58
 */
@RestController
@RequestMapping("/user")
@Api(value = "UserController|用户相关的前端控制器")
public class UserController {

    @Autowired
    IUserService userService;
    
    @Autowired
    ITSysUserNumService iTSysUserNumService;
	
    @Value("${system.defaultPwd}")
    private String defaultPwd;
    
    @Autowired
    IClueService clueService;
    @Autowired
    IUpdateRecordService updateRecordService;

    /**
     * 查询所有用户
     */
    @GetMapping("/list")
    @RequiresRoles("SYSADMIN")
    @ApiOperation(value = "查询用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userMobile", value = "手机号", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userEmail", value = "邮箱", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "roleId", value = "角色", required = false, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "userStatus", value = "用户状态", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页", required = false, dataType = "Long", paramType = "query") })
    public PageResult<UserInfo> list(@ApiIgnore QueryUser user, @ApiIgnore Page<UserInfo> page) {
        Page<UserInfo> pageUser = userService.selectUserList(page, user);
        PageResult<UserInfo> pageResult = new PageResult<UserInfo>(pageUser.getRecords().size(), pageUser.getRecords());
        return pageResult;
    }

    /**
     * 添加用户
     */
    @PostMapping("/create")
    @ApiOperation(value = "添加用户")
    public Result<?> create(@RequestBody @Valid CreateUser user) {
    	
//    	QueryWrapper<User> ew = new QueryWrapper<>();
//    	ew.ne("user_status", 0);
    	
//    	if(iTSysUserNumService.getById("9527").getMaxUserNum() <= userService.list(ew).size())
//    	{
//    		throw new JeecgBootException("当前可创建用户数已达上限，请联系系统客服添加！");
//    	}
    	
        return new Result<>().success(userService.createUser(user)?"添加成功":"添加失败，请重试");
    }

    /**
     * 修改用户
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新用户信息")
    public Result<?> update(@RequestBody UpdateUser user) {
        boolean result = userService.updateUser(user);
        if (result) {
            return new Result<>().success("修改成功");
        } else {
            return new Result<>().error("修改失败");
        }
    }

    /**
     * 修改自己密码
     */
    @PostMapping("/pwd")
    @ApiOperation(value = "用户修改密码")
	public Result<?> updatePassword(@RequestBody UpdateUser useru,HttpServletRequest request) {
        String newPwd = useru.getNewPwd();
        if (newPwd.equals("123456")) {
            return new Result<>().error("密码不得设置为初始密码");
        }
        String oldPwd = useru.getOldPwd();
        if (StringUtils.isEmpty(newPwd) || StringUtils.isEmpty(oldPwd)) {
            return new Result<>().error("密码不能为空");
        }
        
        String userAccount = JwtUtil.getUserAccountByToken(request);
        User tempUser = userService.queryUserByAccount(userAccount);
        if (tempUser == null || !BCrypt.checkpw(oldPwd, tempUser.getUserPassword())) {
            return new Result<>().error("原密码错误");
        }
        User user = new User();
        user.setId(tempUser.getId());
        String cryptPwd = BCrypt.hashpw(newPwd, BCrypt.gensalt());
		// userEntity.setArea("110001");
		user.setUserPassword(cryptPwd);
        user.setUserStatus("1");
        boolean result = userService.updateById(user);
        if (result) {
            return new Result<>().success("修改成功");
        } else {
            return new Result<>().error("修改失败");
        }
    }

    /**
     * 删除用户
     */
    @PostMapping("/delete/{userId}")
    @ApiOperation(value = "删除用户")
    @ApiImplicitParam(paramType = "path", name = "userId", value = "用户ID", required = true, dataType = "Long")
    public Result<?> delete(@PathVariable("userId") Long userId) {
        if (null == userId) {
            return new Result<>().error("用户ID不能为空");
        }
        
        QueryWrapper<Clue> ew = new QueryWrapper<>();
        ew.and(e->e.eq("creator", userId).or().eq("owner_id", userId).or().eq("operator", userId));
        List<Clue> roleList = clueService.list(ew);
        if (!CollectionUtils.isEmpty(roleList)) {
        	throw new JeecgBootException("该用户存在线索记录，不可删除！");
        }
        
        QueryWrapper<UpdateRecord> ew1 = new QueryWrapper<>();
        ew1.eq("creator", userId);
        List<UpdateRecord> updateRecordList = updateRecordService.list(ew1);
        if (!CollectionUtils.isEmpty(updateRecordList)) {
        	throw new JeecgBootException("该用户存在跟进记录，不可删除！");
        }
        
        
        boolean result = userService.deleteUser(userId);
        if (result) {
            return new Result<>().success("删除成功");
        } else {
            return new Result<>().error("删除失败");
        }
    }

    /**
     * 重置密码
     */
    @PostMapping("password/{userId}")
    @ApiOperation(value = "管理员重置用户密码")
    @ApiImplicitParam(paramType = "path", name = "userId", value = "用户ID", required = true, dataType = "Long")
    public Result<?> resetPassword(@PathVariable("userId") Long userId) {
        if (null == userId) {
            return new Result<>().error("用户ID不能为空");
        }
        //UpdateUser user = new UpdateUser();
        User userEntity = new User();
        userEntity.setId(userId);
        userEntity.setUserPassword(defaultPwd);
        String pwd = userEntity.getUserPassword();
		if (!StringUtils.isEmpty(pwd)) {
			String cryptPwd = BCrypt.hashpw(pwd, BCrypt.gensalt());
			userEntity.setUserPassword(cryptPwd);
		}
        boolean result = userService.updateById(userEntity);
        if (result) {
            return new Result<>().success("重置成功");
        } else {
            return new Result<>().error("重置失败");
        }
    }

    /**
     * 修改用户状态
     */
    @PostMapping("/status/{userId}/{status}")
    @RequiresRoles("SYSADMIN")
    @ApiOperation(value = "管理员修改用户状态")
	/* @AroundLog(name = "管理员修改用户状态") */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "status", value = "用户状态", required = true, dataType = "String", paramType = "path") })
    public Result<?> updateStatus(@PathVariable("userId") Long userId, @PathVariable("status") String status) {
        if (null == userId || StringUtils.isEmpty(status)) {
            return new Result<>().error("ID和状态不能为空");
        }
        User user = new User();
        user.setId(userId);
        user.setUserStatus(status);
        
        QueryWrapper<User> ew = new QueryWrapper<>();
    	ew.ne("user_status", 0);
    	if(iTSysUserNumService.getById("9527").getMaxUserNum() <= userService.list(ew).size())
    	{
    		throw new JeecgBootException("当前可创建用户数已达上限，请联系系统客服添加！");
    	}
        
        boolean result = userService.updateById(user);
        if (result) {
            return new Result<>().success("修改成功");
        } else {
            return new Result<>().error("修改失败");
        }
    }

    /**
     * 个人修改用户信息，限制修改字段
     */
    @PostMapping("/update/info")
    @RequiresAuthentication
    @ApiOperation(value = "用户修改个人信息")
	public Result<?> updateInfo(@RequestBody UpdateUser user,HttpServletRequest request) {
    	String userAccount = JwtUtil.getUserAccountByToken(request);
        User tempUser = userService.queryUserByAccount(userAccount);
        User userEntity = new User();
        userEntity.setId(tempUser.getId());
        userEntity.setUserName(user.getUserName());
        userEntity.setUserSex(user.getUserSex());
        boolean result = userService.updateById(userEntity);
        if (result) {
            return new Result<>().success("修改成功");
        } else {
            return new Result<>().error("修改失败");
        }
    }
}
